//
//  HXDHomeTableViewController.swift
//  weibo
//
//  Created by huxuedong on 15/12/5.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit
import SVProgressHUD

private let ID = "cell"

class HXDHomeTableViewController: HXDVisitorTableViewController {
    
    var statusListViewModel: HXDStatusListViewModel = HXDStatusListViewModel()
    //上拉加载视图(菊花)
    private lazy var upLoadView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        view.color = UIColor.orangeColor()
        //view.sizeToFit()
        return view
    }()
    //实例化刷新控制器
    private var hxdRefreshControl: HXDRefreshControl = HXDRefreshControl()
    //下拉刷新的提醒框
    private lazy var downLoadNoticeLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(13)
        label.textAlignment = .Center
        label.hidden = true
        var frame = label.frame
        frame.size = CGSizeMake(kScreenW, 35)
        frame.origin.y = 64 - 35
        label.frame = frame
        return label
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        //用户没有登录
        if !userLogin {
            //设置访客视图的图片和文字
            visitorView?.setVisitorInfo(imageName: nil, message: nil)
            return
        }
        setupUI()
        loadData()
    }
    
    private func setupUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "navigationbar_friendsearch"), style: .Plain, target: self, action: "addFriends")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "navigationbar_pop"), style: .Plain, target: self, action: "addFriends")
        setupTableView()
    }
    
    @objc private func addFriends() {
        let tempViewController = HXDTempViewController()
        navigationController?.pushViewController(tempViewController, animated: true)
    }
    
    private func setupTableView() {
        //注册并创建cell
        tableView.registerClass(HXDStatusTableViewCell.self, forCellReuseIdentifier: ID)
        //设置cell的高度可以自动计算
        tableView.rowHeight = UITableViewAutomaticDimension
        //预设行高
        tableView.estimatedRowHeight = 200
        //隐藏cell之间的分割线
        tableView.separatorStyle = .None
        tableView.tableFooterView = upLoadView
        hxdRefreshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        tableView.addSubview(hxdRefreshControl)
    }

}

extension HXDHomeTableViewController {
    
    //数据源方法，返回行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList?.count ?? 0
    }
    
    ////数据源方法，设置cell的内容
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! HXDStatusTableViewCell
        //设置cell不可点击
        cell.selectionStyle = .None
        cell.statusViewModel = statusListViewModel.statusList![indexPath.row]
        return cell
    }
    
    //代理方法，cell将要显示时调用
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        //菊花不转，并且当前行数是数组中最后一个元素
        if !upLoadView.isAnimating() && indexPath.row == (statusListViewModel.statusList?.count)! - 1 {
            //让菊花转
            upLoadView.startAnimating()
            loadData()
        }
    }
    
}

extension HXDHomeTableViewController {
    
    @objc private func loadData() {
        statusListViewModel.loadData(upLoadView.isAnimating()) { (count, isSuccessed) -> () in
            if isSuccessed {
                self.tableView.reloadData()
                if !self.upLoadView.isAnimating() {
                    self.showDownLoadNotice(count)
                }
            } else {
                SVProgressHUD.showErrorWithStatus("数据加载失败，请检查网络设置！")
            }
            self.endLoad()
        }
    }
    
    private func endLoad() {
        //加载完成后，停止菊花转动
        upLoadView.stopAnimating()
        //刷新控制器停止刷新
        hxdRefreshControl.endRefresh()
    }
    
    private func showDownLoadNotice(count: Int) {
        if downLoadNoticeLabel.hidden == false {
            return
        }
        //判断提示信息Label是否被添加
        if downLoadNoticeLabel.superview == nil {
            if let navigationController = self.navigationController {
                //将提示信息Label添加到导航控制器，并且放在导航条下面
                navigationController.view.insertSubview(downLoadNoticeLabel, belowSubview: navigationController.navigationBar)
            }
        }
        //如果没有更新的微博
        if count == 0 {
            self.downLoadNoticeLabel.text = "没有可以更新的数据"
        } else {
            self.downLoadNoticeLabel.text = "更新了\(count)条数据"
        }
        downLoadNoticeLabel.hidden = false
        UIView.animateWithDuration(1, animations: { () -> Void in
            //执行动画，将提示信息向下平移
            self.downLoadNoticeLabel.transform = CGAffineTransformMakeTranslation(0, self.downLoadNoticeLabel.frame.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    //将提示信息恢复初始位置
                    self.downLoadNoticeLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.downLoadNoticeLabel.hidden = true
                })
        }
    }
    
}
